//
//  MWSettingViewController.swift
//  mggz
//
//  Created by QinWei on 2018/3/12.
//  Copyright © 2018年 爱丽丝的梦境. All rights reserved.
//

import UIKit

class MWSettingViewController: WarningBaseController {
    var cTStatus:CertificationStatus?
    var signState:SignedType?
    var currentModel:ProjectModel?
    
    var signOutAlertView:TWLAlertView?
    fileprivate var _tableView: UITableView!
    fileprivate var tableView: UITableView {
        get {
            if _tableView != nil {
                return _tableView
            }
            _tableView = UITableView(frame: CGRect.zero, style: .grouped)
            _tableView.delegate = self
            _tableView.dataSource = self
            _tableView.backgroundColor = UIColor.clear
            _tableView.separatorStyle = .none
            _tableView.tableFooterView = UIView()
            _tableView.showsVerticalScrollIndicator = false
            
            _tableView.register(UserCommonCell.self, forCellReuseIdentifier: "\(UserCommonCell.self)")
            
            return _tableView
        }
    }
    fileprivate var itemNames:[[String]]?
    fileprivate var itemImages:[[String]]?
    
    
    /***本地变量***/
    fileprivate var userInfoModel: UserInfoModel? //用户信息模型
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        //        WWUser.sharedInstance.ensureCertificationStatus { (show) in
        //            self.setupWarningContent(show)
        //        }
        //  WWUser.sharedInstance.ensureCertificationStatus(self)
        self.checkCertificationStatus()
        self.setupTableData()
        self.getData()
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        WWProgressHUD.dismiss()
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "设置"
        self.view.backgroundColor = colorWith255RGB(248, g: 248, b: 248)
        if #available(iOS 11.0, *) {
            self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentBehavior.scrollableAxes
        }
        
        //self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "测试", style: .done, target: self, action: #selector(doRightAction))
        
        NotificationCenter.default.addObserver(self, selector: #selector(doNotificationAction), name: NSNotification.Name.init(rawValue: kNotificationUserInfoChanged), object: nil)
        
        self.baseView.addSubview(self.tableView)
        self.tableView.snp.makeConstraints { (make) in
            make.edges.equalTo(self.baseView)
        }
        
        if #available(iOS 11.0, *) {
            self.tableView.contentInset = UIEdgeInsets(top: -33, left: 0, bottom: 0, right: 0)
        }
        
        
        
        
        
      //  self.tableView.contentInset = UIEdgeInsets(top: -33, left: 0, bottom: 0, right: 0)
        
    }
    fileprivate func setupTableData(){
        self.itemNames = NSMutableArray() as? [[String]]
        self.itemImages = NSMutableArray() as? [[String]]
        if self.cTStatus == .authenticated{
            itemNames = [["实名认证","更改手机号","密码设置"], ["提醒设置", "清空缓存","我的工作轨迹"],["联系我们","给太公民工评分", "关于太公民工","退出"]]
            itemImages = [["Icon_借款资料认证", "Icon_手机号","Icon_修改密码"], ["Icon_消息提醒", "Icon_清空缓存","gzgj"],["Icon_意见反馈","Icon_关于","Icon_好评","au_tuichu"]]
            
        }else{
            itemNames = [["更改手机号","密码设置"], ["提醒设置", "清空缓存","我的工作轨迹"],["联系我们","给太公民工评分", "关于太公民工","退出"]]
            itemImages = [["Icon_手机号","Icon_修改密码"], ["Icon_消息提醒", "Icon_清空缓存","gzgj"],["Icon_意见反馈","Icon_关于","Icon_好评","au_tuichu"]]
        }
        self.tableView.reloadData()
    }
    private func checkCertificationStatus() {
        CertificationModel.checkCertificationStatus({ (response) in
            if response.success {
                WWUser.sharedInstance.ensureCertificationStatus(self)
            }
            else {
            }
        })
    }
    func doRightAction() {
        let vc = ViewController()
        vc.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    @objc func doNotificationAction() {
        self.getData()
    }
    
    @objc func doLoginOutAction() {
        if self.signState == .signedIn{
            
            self.signOutAlertView = TWLAlertView.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT))
            let advanceSureView = LoginOutSignView(frame: CGRect(x: 0, y: 0, width: 280, height: 175))
            advanceSureView.loginButton.addTarget(self, action: #selector(loginOutActionClick), for: .touchUpInside)
            advanceSureView.cancelButton.addTarget(self, action: #selector(signViewCancel), for: .touchUpInside)
        self.signOutAlertView?.initWithCustomView(advanceSureView, frame: CGRect(x: 0, y: 0, width: 280, height: 175))
            let keyWindow = UIApplication.shared.keyWindow
            keyWindow?.addSubview(self.signOutAlertView!)
            
        }else{
        let alert  = UIAlertController(title: "确认退出吗？", message: nil, preferredStyle: .alert)
        
        let cancel = UIAlertAction(title: "取消", style: .cancel) { (action) in
            
        }
        cancel .setValue(UIColor.black, forKey: "titleTextColor")
        let choose = UIAlertAction(title: "确定", style: .default) { (action) in
            self.loginOutDetailClick()
        }
        alert.addAction(cancel)
        alert.addAction(choose)
        self.present(alert, animated: true) {
        }
            
    }
    }
    
    @objc fileprivate func signViewCancel(){
        self.signOutAlertView?.cancleView()
    }
    @objc fileprivate func loginOutActionClick(){
        self.signOutAlertView?.cancleView()
        self.loginOutDetailClick()
    }
    fileprivate func signOutDataSend(){
        
        var guid: String?
        
        let _dispatchGroup = DispatchGroup()
        
        _dispatchGroup.enter()
        UserModel.getGuid { (response) in
            if response.success {
                guid = response.value
            }
            else{
                WWError(response.message)
            }
            _dispatchGroup.leave()
        }
        
        _dispatchGroup.notify(queue: DispatchQueue.main) {
            guard guid != nil else {
                WWError("guid是空的")
                return
            }
            guard let demandBaseMigrantWorkerID = self.currentModel?.demandBaseMigrantWorkerID  else{
                return
            }
    RecordModel.record(guid:guid!,demandBaseMigrantWorkerId: demandBaseMigrantWorkerID, signedType: SignedType.signedOut){(response) in
                if response.success {
                    WWSuccess("签出成功")
                    
                }
                else {
                    WWError(response.message)
                }
            }
        }
    }
    
    fileprivate func loginOutDetailClick(){
        
       
        (UIApplication.shared.delegate as! AppDelegate).setTags(nil)
        RemoteNotificationModel.removeClient { (response) in
            if !response.success {
                LoginType = -1
                LoginAuthenticationService.setupIngore(username: "2")
                TrackUploadService.sharedInstance.stop()
                TrackUploadService.sharedInstance.stopBackGroundLocation()
                WWUser.sharedInstance.loginOut()
                
                let vc = LoginViewController()
            UIApplication.shared.delegate?.window!?.rootViewController = vc
                
            }
            else {
                LoginType = -1
            LoginAuthenticationService.setupIngore(username: "2")
                TrackUploadService.sharedInstance.stop()
                TrackUploadService.sharedInstance.stopBackGroundLocation()
                WWUser.sharedInstance.loginOut()
                
                let vc = LoginViewController()
            UIApplication.shared.delegate?.window!?.rootViewController = vc
            }
        }
       
    }
    fileprivate func getData() {
        UserInfoModel.getMigrantWorkInfo { (response) in
            if response.success {
                self.userInfoModel = response.value
                self.tableView.reloadSections(IndexSet.init(integer: 0), with: .automatic)
            }
            else {
                // WWError(response.message)
            }
        }
    }
    
    //alert删除缓存
    fileprivate func alertDeleteCache(completion:@escaping () -> Void) {
        let alertController = UIAlertController(title:"提示", message: "删除缓存？", preferredStyle: .alert)
        
        let okAction = UIAlertAction(title: "确认", style: .default) { (action) in
            Tool.clearCache()
            completion()
        }
        
        let cancenlAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
        
        alertController.addAction(okAction)
        alertController.addAction(cancenlAction)
        self.present(alertController, animated: true, completion: nil)
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }

   
}

extension MWSettingViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if self.cTStatus == .authenticated{
            return [3,3,4][section]
        }
        return [2,3,4][section]
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 3
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        return 45
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "\(UserCommonCell.self)", for: indexPath) as! UserCommonCell
        cell.accessoryType = .disclosureIndicator
        cell.cellImageView.image = UIImage(named: itemImages![indexPath.section][indexPath.row])
        cell.itemNameLabel.text = self.itemNames![indexPath.section][indexPath.row]
        cell.itemDetailLabel.text = ""
        
        if indexPath.section == 0 {
            if self.cTStatus == .authenticated{
            if indexPath.row == 0{
                cell.itemDetailLabel.text = "已认证"
            }
            if indexPath.row == 1 {
                guard let model = self.userInfoModel else {
                    let username = LoginAuthenticationService.getLastUsernameAndPassword().0
                    cell.itemDetailLabel.text = Tool.securityPhoneNumber(username ?? "")
                    return cell
                }
                guard let phoneNumber = model.cellPoneNumber, phoneNumber.count == 11  else{
                    return cell
                }
                
                cell.itemDetailLabel.text = Tool.securityPhoneNumber(phoneNumber)
            }
            }else{
                if indexPath.row == 0 {
                    guard let model = self.userInfoModel else {
                        let username = LoginAuthenticationService.getLastUsernameAndPassword().0
                        cell.itemDetailLabel.text = Tool.securityPhoneNumber(username ?? "")
                        return cell
                    }
                    guard let phoneNumber = model.cellPoneNumber, phoneNumber.count == 11  else{
                        return cell
                    }
                    
                  cell.itemDetailLabel.text = Tool.securityPhoneNumber(phoneNumber)
                    
                }
            }
        }
        if indexPath.section == 1 {
            if indexPath.row == 1 {
                let size = Tool.fileSizeOfCache()
                cell.itemDetailLabel.text = "\(size)" + "M"
            }
        }
        
        return cell
        
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        
        if indexPath.section == 0 {
            if self.cTStatus == .authenticated{
            if indexPath.row == 0 {//认证资料
                let haveBeenCT = HaveBeenCTViewController(nibName: "HaveBeenCTViewController", bundle: nil)
            self.navigationController?.pushViewController(haveBeenCT, animated: true)
            }
            if indexPath.row == 1 {//更改手机号码
                guard self.userInfoModel != nil else {
                    return
                }
                let vc = ModifyPhoneNumberController()
                vc.hidesBottomBarWhenPushed = true
                vc.userInfoModel = self.userInfoModel
            self.navigationController?.pushViewController(vc, animated: true)
            }
            if indexPath.row == 2 {//修改密码
                let passwordSet = PassWordSetViewController(nibName: "PassWordSetViewController", bundle: nil)
                passwordSet.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(passwordSet, animated: true)
            }
            }else{
                if indexPath.row == 0 {//更改手机号码
//                    guard self.userInfoModel != nil else {
//                        return
//                    }
                    let vc = ModifyPhoneNumberController()
                    vc.hidesBottomBarWhenPushed = true
                    vc.userInfoModel = self.userInfoModel
                self.navigationController?.pushViewController(vc, animated: true)
                }
                if indexPath.row == 1 {//修改密码
                    let passwordSet = PassWordSetViewController(nibName: "PassWordSetViewController", bundle: nil)
                    passwordSet.hidesBottomBarWhenPushed = true
                self.navigationController?.pushViewController(passwordSet, animated: true)
                    
                }
            }
        }
        if indexPath.section == 1 {
            if indexPath.row == 0 {//消息提醒
                //                #if DEBUG
                //                    WWInform("本功能还没有")
                //                #else
                //                #endif
                let vc = MGNotiStateViewController(nibName: "MGNotiStateViewController", bundle: nil)
                vc.hidesBottomBarWhenPushed = true
             self.navigationController?.pushViewController(vc, animated: true)
            }
            
            
            if indexPath.row == 1 {//清空缓存
                self.alertDeleteCache(completion: {
                    tableView.reloadRows(at: [indexPath], with: .automatic)
                })
            }
            if indexPath.row == 2{ //我的工作轨迹
                
               let myWorkTrack = MyWorkTrackViewController(nibName: "MyWorkTrackViewController", bundle: nil)
                myWorkTrack.hidesBottomBarWhenPushed = true;
            self.navigationController?.pushViewController(myWorkTrack, animated: true)
            }
        }
        if indexPath.section == 2 {
            if indexPath.row == 0 { //意见反馈
               let contackUs = ContactUsViewController(nibName: "ContactUsViewController", bundle: nil)
                contackUs.hidesBottomBarWhenPushed = true
                self.navigationController?.pushViewController(contackUs, animated: true)
        
            }
            if indexPath.row == 1 {//评分
                let alert = UIAlertController(title: "给太公民工评分!", message: "", preferredStyle: .alert)
                let gotoAppstore = UIAlertAction(title: "前往评分", style: .default, handler: { (action) in
                let url = NSURL(string: "https://itunes.apple.com/cn/app/%E5%A4%AA%E5%85%AC%E6%B0%91%E5%B7%A5/id1262331278?mt=8")
                UIApplication.shared.openURL(url! as URL)
                    
                })
                let refuseApp = UIAlertAction(title: "取消", style: .cancel, handler: { (action) in
                    
                })
                alert.addAction(gotoAppstore)
                alert.addAction(refuseApp)
                self.present(alert, animated: true, completion: {
                    
                })
            }
            if indexPath.row == 2{
                
            let vc = AbountViewController()
            vc.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(vc, animated: true)
            }
            
            if indexPath.row == 3 {
                self.doLoginOutAction()
            }
        }
        
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        
        if section == 0{
            return 0.1
        }
        return 10
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.1
    }
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let view = UIView()
        view.frame = CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 0.1)
        return view
    }
}
